from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from meiduo_mall import settings


# 加密
def generic_email_verify_token(user_id):
    # 创建实例
    s = Serializer(secret_key=settings.SECRET_KEY, expires_in=3600 * 24)
    # 加密数据
    access_token = s.dumps({'openid': user_id})

    # 若不解码则返回类型为bytes
    return access_token.decode()


# 解密
def check_verify_token(token):
    # 1. 创建实例
    s = Serializer(secret_key=settings.SECRET_KEY, expires_in=3600 * 24)
    # 2. 解密数据(可能有异常)
    try:
        result = s.loads(token)
    except Exception as e:
        return None
    # 3.获取数据
    return result.get('user_id')
